/**
 * http请求工具类
 */
import axios from 'axios'
import qs from 'qs'
import config from '@/config/config'

// 创建axios实例
const service = axios.create({
  baseURL: config.baseUrl,
  timeout: config.urlTimeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    // 请求参数序列化
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

//http response 拦截器
service.interceptors.response.use(
  response => {
    if (response.data.errCode === 200) {
      return Promise.resolve(response)
    } else if (response.data.errCode === 203) {
      sessionStorage.removeItem("token")
      location.reload()
      return Promise.reject(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default service